
/*
    pbrt source code Copyright(c) 1998-2012 Matt Pharr and Greg Humphreys.

    This file is part of pbrt.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are
    met:

    - Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.

    - Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
    IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
    TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
    PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
    HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

 */


#include "stdafx.h"
#include "integrators/path.h"
#include "scene.h"
#include "intersection.h"
#include "paramset.h"


PathData::PathData(const Scene *scene, const Renderer* renderer, RNG &rng,
	MemoryArena &arena) : scene(scene), renderer(renderer), 
	rng(rng), arena(arena){
}


PathIntegrator::PathIntegrator(int md) {
	maxDepth = md;
}


PathIntegrator::~PathIntegrator() {
	delete lightDistribution;
}


void PathIntegrator::Preprocess(const Scene *scene, const Camera *camera,
	const Renderer *renderer) {
	lightDistribution = ComputeLightSamplingCDF(scene);
}


void PathIntegrator::RequestSamples(Sampler *sampler, Sample *sample, 
	const Scene *scene) {
	lightSampleOffset = LightSampleOffsets(maxDepth, sample);
	bsdfSampleOffset = BSDFSampleOffsets(maxDepth, sample);
	pathSampleOffset = BSDFSampleOffsets(maxDepth, sample);
	lightNumOffset = sample->Add1D(maxDepth);
}


IntegrationResult PathIntegrator::Li(const Scene *scene, const Renderer *renderer,
        const RayDifferential &ray, const Intersection &isect,
        const Sample *sample, RNG &rng, MemoryArena &arena) const {
    // Declare common path integration variables
    Spectrum L(0.f), escapedAlpha(0.f);
	RayDifferential escapedRay;
    bool prevSpecular = true;
	PathData data(scene, renderer, rng, arena);
	PathVertex *path = new PathVertex[maxDepth];

	int pathLength = GeneratePath(data, ray, isect, sample, path, 
		&escapedRay, &escapedAlpha);

	for (int i = 0; i < pathLength; i++) {
		// Initialize basic variables for camera path vertex
		const PathVertex &v = path[i];

		// Add emitted light from vertex if appropriate
		if (prevSpecular)
			L += v.alpha * v.isect.Le(v.wPrev);

		// Add direct illumination for path vertex
		L += DirectLightingVertex(data, sample, i, v);

		prevSpecular = v.specularBounce;
	}

	// Add contribution of escaped ray, if any
	if (!escapedAlpha.IsBlack() && prevSpecular)
	for (uint32_t i = 0; i < scene->lights.size(); ++i)
		L += (escapedAlpha) * scene->lights[i]->Le(escapedRay);
	
	delete[] path;
	return IntegrationResult(L);
}


Spectrum PathIntegrator::DirectLightingVertex(PathData &data, const Sample *sample,
	int pathIdx, const PathVertex &v) const {
	Spectrum L(0.f);
	const Point &p = v.bsdf->dgShading.p;
	const Normal &n = v.bsdf->dgShading.nn;

	float lightPdf;
	uint32_t lightNum = lightDistribution->SampleDiscrete(
		sample->oneD[lightNumOffset][pathIdx], &lightPdf);
	const Light *light = data.scene->lights[lightNum];
	BSDFSample bsdfSample(sample, bsdfSampleOffset, pathIdx);
	LightSample lightSample(sample, lightSampleOffset, pathIdx);

	L = v.alpha *
		EstimateDirect(data.scene, data.renderer, data.arena, light, p, n, v.wPrev,
		v.isect.rayEpsilon, sample->time, v.bsdf, data.rng, lightSample, bsdfSample,
		BxDFType(BSDF_ALL & ~BSDF_SPECULAR)) / lightPdf;
	return L;
}


uint32_t PathIntegrator::GeneratePath(PathData &data, const RayDifferential r, 
	const Intersection &firstIsect, const Sample* sample, PathVertex *path, 
	RayDifferential *escapedRay, Spectrum *escapedAlpha) const {
	// Declare common path integration variables
	Spectrum pathThroughput = 1.f;
	RayDifferential ray(r);

	PathVertex *v = &path[0];
	v->isect = firstIsect;

	int length = 0;
	for (; length < maxDepth; length++) {
		// Try to generate next vertex of ray path
		v = &path[length];
		if (length > 0) {
			if (!data.scene->Intersect(ray, &v->isect)) {
				*escapedAlpha = pathThroughput;
				*escapedRay = ray;
				break;
			}
		}
		SavePathVertexInfo(v, ray, pathThroughput, data.arena);

		// Sample BSDF to get new path direction
		float pdf;
		BxDFType flags;
		BSDFSample BSDFSampleOut = BSDFSample(sample, pathSampleOffset, length);
		Spectrum f = v->bsdf->Sample_f(-ray.d, &v->wNext, BSDFSampleOut, &pdf,
			BSDF_ALL, &flags);
		v->specularBounce = (flags & BSDF_SPECULAR) != 0;
		v->nSpecularComponents = v->bsdf->NumComponents(BxDFType(BSDF_SPECULAR |
			BSDF_REFLECTION | BSDF_TRANSMISSION));

		if (f.IsBlack() || pdf == 0. || !RussianRoulette(data, *v, f, pdf, &ray,
			&pathThroughput)) {
			return length + 1;
		}
	}
	return length;
}


void PathIntegrator::SavePathVertexInfo(PathVertex *v, const RayDifferential &ray,
	const Spectrum &pathThroughput, MemoryArena &arena) const {
	v->alpha = pathThroughput;
	BSDF *bsdf = v->isect.GetBSDF(ray, arena);
	v->bsdf = bsdf;
	v->wPrev = -ray.d;
}


bool PathIntegrator::RussianRoulette(PathData &data, PathVertex &v, Spectrum &f, 
	float pdf, RayDifferential *ray, Spectrum *alpha) const {
	// Terminate path with RR or prepare for finding next vertex
	const Point &p = v.bsdf->dgShading.p;
	const Normal &n = v.bsdf->dgShading.nn;
	Spectrum pathScale = f * AbsDot(v.wNext, n) / pdf;
	float rrSurviveProb = min(1.f, pathScale.y());

	if (data.rng.RandomFloat() > rrSurviveProb) return false;

	*alpha *= pathScale / rrSurviveProb;
	*alpha *= data.renderer->Transmittance(data.scene, *ray, NULL, data.rng, 
		data.arena);
	*ray = RayDifferential(p, v.wNext, *ray, v.isect.rayEpsilon);

	return true;
}


PathIntegrator *CreatePathSurfaceIntegrator(const ParamSet &params) {
    int maxDepth = params.FindOneInt("maxdepth", 5);
    return new PathIntegrator(maxDepth);
}


